package com.ruoyi.user.service;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.user.domain.AppUserRole;
import com.ruoyi.user.domain.LoginAppUser;
import com.ruoyi.system.api.domain.User;
import com.ruoyi.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class LoginService {

    private static final String SYS_LOGIN_CODE = "CODE";

    @Autowired
    private AppRoleMenuService appRoleMenuService;

    @Resource
    private IUserService iUserService;

    @Autowired
    private AppUserRoleService appUserRoleService;

    @Autowired
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 登录
     */
    @Transactional
    public LoginAppUser login(LoginAppUser loginAppUser) throws Exception {
        if(StringUtils.isAnyBlank(loginAppUser.getPhone())){
            throw new ServiceException("手机号不能为空");
        }

        User user = new User();
        AppUserRole appRole = new AppUserRole();
        user.setPhone(loginAppUser.getPhone());

        // 查询用户，不存在则创建 给新创建的用户赋予角色
        List<User> users = userMapper.selectUserList(user);
        if (users == null || users.isEmpty()){
            user.setRegTime(new Date());
            userMapper.insertUser(user);
            // 设置分配角色
            appRole.setAppUserId(user.getId());
            appRole.setRoleId(2);
            appUserRoleService.addAppUserRole(appRole);
        }else {
            user = users.get(0);
        }
        // 查询用户角色
        AppUserRole appUserRole = new AppUserRole();
        appUserRole.setAppUserId(user.getId());

        // 查询角色关键字
        Set<String> roles = appUserRoleService.getAppUserRole(appUserRole);
        loginAppUser.setRoles(roles);

        // 查询角色id
        List<Integer> roleId = appUserRoleService.getRoleId(user.getId());

        // 查询用户菜单权限
        Set<String> permissions = appRoleMenuService.getAppRoleMenu(roleId.get(0));
        loginAppUser.setPermissions(permissions);


        // 验证手机号和验证码是否一致
        String codeCache = (String)redisTemplate.opsForValue().get(SYS_LOGIN_CODE + loginAppUser.getPhone());

        if (codeCache == null){
            throw new ServiceException("验证码已过期或未填写");
        }
        if(!codeCache.equals(loginAppUser.getCode())){
            throw new ServiceException("验证码错误");
        }
        loginAppUser.setUser(user);
        return loginAppUser;
    }

    public void getCode(String phone){
        String codeCache = (String)redisTemplate.opsForValue().get(SYS_LOGIN_CODE + phone);
        if (codeCache!=null){
            throw new ServiceException("请勿重复发送");
        }
        // 生成四位数验证码
        Random rand = new Random();
        int code = rand.nextInt(9000)+1000;

        // TODO 后期更改为真正的短信验证 SendMessUtil.sendMess(user.getPhone(), code);
        redisTemplate.opsForValue().set(SYS_LOGIN_CODE+phone,String.valueOf(code),60, TimeUnit.SECONDS);
        System.out.println(code);
    }
}
